import { createStore } from 'vuex'
import { login, getInfo, logout } from "@/api/admin/manager"
import { setToken, removeToken } from '@/composables/auth'



const store = createStore({
    state() {
        return {
            // 用户信息
            user: {},
            // 侧边栏宽度
            asideWidth: "250px"
        }
    },
    mutations: {
        // 设置用户信息
        SET_USER_INFO(state, user) {
            state.user = user
        },
        // 设置侧边栏宽度
        handleAsideWidth(state) {
            state.asideWidth = state.asideWidth === "250px" ? "64px" : "250px"
        }
    },
    actions: {
        // 获取用户信息
        getInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    commit("SET_USER_INFO", res)
                    resolve(res)
                })
                    .catch(err => reject(err))
            })
        },
        // 登录
        login({ commit }, { username, password }) {
            return new Promise((resolve, reject) => {

                //console.log(username, password)
                login(username, password).then(res => {
                    //console.log(res)
                    setToken(res.token)
                    resolve(res)
                }).catch(err => reject(err))
            })
        },
        logout({ commit }) {
            // 清除token
            removeToken();

            // 清除用户信息
            commit("SET_USER_INFO", {});

        }
    }
})

export default store;